//
//  HomeTableViewController.swift
//  Super_WeiBo
//
//  Created by 梁超 on 16/3/15.
//  Copyright © 2016年 lc. All rights reserved.
//

import UIKit
import SDWebImage

let SuperChao_HomeReuseIdentifier = "SuperChao_HomeReuseIdentifier"
class HomeTableViewController: BaseTableViewController {

    ///  保存微博数据
    var statuses: [Status]?
    {
        didSet{
            // 设置完数据后刷新表格
            tableView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if !userLogin
        {
            visitorView?.setupVisitorInfo(true, imageName: "visitordiscover_feed_image_house", message: "首页界面")
            return
        }
        
        // 设置导航条
        setupNav()
        
        // 注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HomeTableViewController.change), name: PopoviewAnimatorWillShow, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HomeTableViewController.change), name: PopoviewAnimatorWillDismiss, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HomeTableViewController.showPhotoBrowser(_:)), name: LCStatusPictureViewSelected, object: nil)
        
        
        
        // 注册cell
        tableView.registerClass(StatusNormalTableViewCell.self, forCellReuseIdentifier: StatusTableViewCellIdentifier.NormalCell.rawValue)
        tableView.registerClass(StatusForwordTableViewCell.self, forCellReuseIdentifier: StatusTableViewCellIdentifier.ForwardCell.rawValue)
        
        // 动态计算cell高度
        tableView.estimatedRowHeight = 200
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        // 添加刷新空间
        refreshControl = HomeRefreshControl()
        refreshControl?.addTarget(self, action: #selector(HomeTableViewController.loadData), forControlEvents: UIControlEvents.ValueChanged)
        
        // 添加刷新提示栏
        navigationController?.navigationBar.insertSubview(newStatusLabel, atIndex: 0)
        
        // 加载微博数据
        loadData()
    }
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
        
    }
    
    /// 上、下拉操作标记(默认为下拉)
    var pullupRefreshFlag = false
    /**
     获取微博数据
     Swift中如果想要调用一个私有方法
     1、去掉 private 前缀；2、增加 @objc 前缀 当做OC方法，就可以动态识别
     */
    @objc private func loadData()
    {
        // 设置下拉刷新微博ID
        var since_id = statuses?.first?.id ?? 0
        
        // 设置上拉加载更多微博ID
        var max_id = 0
        
        // 判断是否为上拉
        if pullupRefreshFlag
        {
            since_id = 0
            max_id = statuses?.last?.id ?? 0
        }
        
        Status.loadStatuses(since_id, max_id: max_id) { (model, error) in
            
            // 停止刷新
            self.refreshControl?.endRefreshing()
            
            if error != nil
            {
                return
            }
            // 下拉刷新
            if since_id > 0
            {
                // 如果是下拉刷新，讲、将获取到的数据拼接到原有数据前面
                self.statuses = model! + self.statuses!
                
                // 显示刷新提醒
                self.showStatusCount(model?.count ?? 0)
            }
            // 上拉加载更多
            else if max_id > 0
            {
                self.statuses = self.statuses! + model!
                self.pullupRefreshFlag = false
            }
            else
            {
                self.statuses = model
            }
            
        }
    }
    
    /**
     显示刷新提示栏
     */
    private func showStatusCount(count: Int)
    {
        newStatusLabel.hidden = false
        newStatusLabel.text = (count == 0) ? "没有新微博" : "\(count)条新微博"
        
        // 利用 transform 完成动画
        UIView.animateWithDuration(1, animations: {
            
            self.newStatusLabel.transform = CGAffineTransformMakeTranslation(0, self.newStatusLabel.frame.height)
            
            }) { (_) in
                
                UIView.animateWithDuration(0.6, animations: {
                    self.newStatusLabel.transform = CGAffineTransformIdentity
                }) { (_) in
                    self.newStatusLabel.hidden = true
                }
        }
        
        // 利用 view自动复位 完成动画，有Bug真机运行会闪屏
        /*
        let rect = newStatusLabel.frame
        // 执行动画
        UIView.animateWithDuration(2, animations: { 
            
            UIView.setAnimationRepeatAutoreverses(true) // 执行玩动画以后自动复位
            self.newStatusLabel.frame = CGRectOffset(rect, 0, 2 * rect.height)
            
            }) { (_) in
                
                self.newStatusLabel.frame = rect
                
        }
         */
    }
    
    /**
     图片浏览器
     */
    func showPhotoBrowser(info: NSNotification)
    {
        // 通过通知传递数据一定判断数据是否存在
        // 判断数据是否有效
        guard let indexPath = info.userInfo![LCStatusPictureViewIndexKey] as? NSIndexPath else
        {
            return
        }
        guard let urls = info.userInfo![LCStatusPictureViewURLKey] as? [NSURL] else
        {
            return
        }
        // 创建图片浏览器
        let vc = PhotoBrowserController(index: indexPath.item, urls: urls)
        // 显示界面
        presentViewController(vc, animated: true, completion: nil)
    }
    
    func change()
    {
        // 修改标题按钮的状态
        let btn = navigationItem.titleView as! TitleButton
        btn.selected = !btn.selected
    }
    
    private func setupNav()
    {
        // 通过创建 UIBarButtonItem 类别的方式创建 btn
        navigationItem.leftBarButtonItem = UIBarButtonItem.creatBarBtn("navigationbar_friendattention", target: self, action: #selector(HomeTableViewController.pressleftBtn))
        navigationItem.rightBarButtonItem = UIBarButtonItem.creatBarBtn("navigationbar_pop", target: self, action: #selector(HomeTableViewController.pressRightBtn))
        
        // 创建导航栏中间视图
        let titleBtn = TitleButton()
        titleBtn.setTitle("Super超 ", forState: UIControlState.Normal)
        
        // titleBtn.addTarget(self, action: "prsssTitleBtn:", forControlEvents: UIControlEvents.TouchUpInside)
        titleBtn.addTarget(self, action: #selector(HomeTableViewController.prsssTitleBtn(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        navigationItem.titleView = titleBtn
    }
    
    func prsssTitleBtn(btn : TitleButton)
    {
        // 创建菜单
        let sb = UIStoryboard(name: "PopoverViewController", bundle: nil)
        let vc = sb.instantiateInitialViewController()
        // 设置专转动画代理
        vc?.transitioningDelegate = popoverAnimator // 一定要定一个变量保存 转场动画 因为代理是弱引用
        // 设置专转动画类型
        vc?.modalPresentationStyle = UIModalPresentationStyle.Custom
        presentViewController(vc!, animated: true, completion: nil)
    }
    
    // MARK: - 懒加载
    // 一定要定一个变量保存 转场动画 因为代理是弱引用
    private lazy var popoverAnimator : PopoverAnimator = {
        let pA = PopoverAnimator()
        pA.presentFrame = CGRect(x: 100, y: 56, width: 200, height: 350)
        
        return pA
    }()
        /// 顶部更新状态栏
    private lazy var newStatusLabel: UILabel = {
       let l = UILabel()
        l.backgroundColor = UIColor.orangeColor()
        l.textAlignment = NSTextAlignment.Center
        l.font = UIFont.systemFontOfSize(15)
        l.textColor = UIColor.whiteColor()
        l.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 44)
        l.hidden = true
        return l
    }()

    /**
     人像按钮
     */
    func pressleftBtn()
    {
        
    }
    
    /**
     扫描二维码
     */
    func pressRightBtn()
    {
        let sb = UIStoryboard(name: "QRCodeViewController", bundle: nil)
        let vc = sb.instantiateInitialViewController()
        presentViewController(vc!, animated: true, completion: nil)
//        navigationController?.pushViewController(vc!, animated: true)
    }
    
    /// 微博行高的缓存, 利用字典作为容器. key就是微博的id, 值就是对应微博的行高
    var rowCache: [Int: CGFloat] = [Int: CGFloat]()
    
    override func didReceiveMemoryWarning() {
        // 清空缓存
        rowCache.removeAll()
    }

}

extension HomeTableViewController
{
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statuses?.count ?? 0
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        // 如果是最后一条数据，触发加载更多操作
        let modelCount = statuses?.count ?? 0
        if modelCount - 5 == indexPath.row
        {
            pullupRefreshFlag = true
            loadData()
        }
        
        // 取出数据
        let status = statuses![indexPath.row]
        
        // 获取cell
        let cell = tableView.dequeueReusableCellWithIdentifier(StatusTableViewCellIdentifier.cellID(status), forIndexPath: indexPath) as! StatusTableViewCell
        // 设置数据
        
        cell.status = status
        
        return cell
    }
    // 返回行高
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        // 1.取出对应行的模型
        let status = statuses![indexPath.row]
        
        // 2.判断缓存中有没有
        if let height = rowCache[status.id]
        {
            return height
        }
        
        // 3.拿到cell
        let cell = tableView.dequeueReusableCellWithIdentifier(StatusTableViewCellIdentifier.cellID(status)) as! StatusTableViewCell
        
        // 4.拿到对应行的行高
        let rowHeight = cell.rowHeight(status)
        
        // 5.缓存行高
        rowCache[status.id] = rowHeight
        
        // 6.返回行高
        return rowHeight
    }
    
}

